package com.jeeplus.modules.sys.web;

import cached.redis.RedisUtil;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.mapper.UserMapper;
import com.jeeplus.modules.sys.security.SystemAuthorizingRealm;
import com.jeeplus.modules.sys.security.UsernamePasswordToken;
import com.jeeplus.modules.sys.service.SystemService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.wxMsg.WeixinUtil;
import groovy.transform.Synchronized;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

import static com.jeeplus.modules.sys.web.LoginController.OAUTH_CODE_URL;

@Controller
@RequestMapping("${adminPath}/wx")
public class WxOauthController extends BaseController {

    @Autowired
    UserMapper userMapper;

    Logger logger = LoggerFactory.getLogger(WxOauthController.class);

    /**
     * 回调地址
     * @param code
     * @return
     * @throws Exception
     */
    @RequestMapping("/outh")
    @Synchronized
    public String outh(String state,String code,HttpServletRequest request) throws Exception{
        String url = "";
        boolean b = true;
        System.out.println("code:=======  " + code);
        System.out.println("state:=======  " + state);
        Map<String,Object> map = WeixinUtil.getUserInfo(code);
        System.out.println(map.get("errcode"));
        if(map.get("errcode").equals("0") || map.get("errcode").equals(0)){
            String userId = map.get("UserId").toString();
            User user = userMapper.getByWxname(userId);
            if(StringUtils.isNotBlank(user.getLoginName())){
                Subject subject = SecurityUtils.getSubject();
                UsernamePasswordToken token = new UsernamePasswordToken(user.getLoginName());
                subject.login(token);
                logger.debug("免密登录。。。。。");
                url =  "redirect:" + adminPath;
            }else {
                url =  "modules/sys/login/sysLogin";
            }
        }else {
            url =  "modules/sys/login/sysLogin";
        }
        return url;
    }

}
